#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
THN HTTP Stack Library
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 04-Nov-11 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Text;

using Thn;
using Thn.IO;
#endregion

namespace Thn.Net.Http
{
    /// <summary>
    /// This parser supports parsing <see cref="IHttpRequest"/>.
    /// </summary>
#if DEBUG || TESTING
    public
#else
    internal
#endif
 class HttpRequestParser : HttpParserBase
    {
        #region Fields
        const byte SpaceCharactorAsByte = (byte)' ';
        #endregion

        #region Properties
        #endregion

        #region On Create Content
        /// <summary>
        /// Create a new instance of <see cref="IHttpContent"/>.
        /// </summary>
        protected override IHttpContent OnCreateContent()
        {
            return new HttpRequest();
        }
        #endregion

        #region On Get Data Size
        /// <summary>
        /// Get number of bytes the data section occupies (if any).
        /// </summary>
        /// <param name="content">The content to get size for.</param>
        /// <returns>Positive value means has data. Zero means no data. Negative means has data but size is unknown.</returns>
        protected override int OnGetDataSize(IHttpContent content)
        {
            int result = 0;

            string value = content.Headers[HttpRequestHeaderNames.Content_Length];
            if (!string.IsNullOrEmpty(value))
            {//Has Content-Length header
                result = int.Parse(value);
            }
            else
            {
                value = content.Headers[HttpRequestHeaderNames.Connection];
                if (!string.IsNullOrEmpty(value))
                {//has Connection header
                    value = value.ToLower();
                    if (value == HttpConnectionValues.Close)
                    {
                        result = -1;
                    }
                    else if (value == HttpConnectionValues.KeepAlive)
                    {
                        result = 0;
                    }
                    else
                    {
                        result = 0;
                        mError = HttpParserFailureReason.NoDataLength;

                        if (NetSettings.PublishWarning) Log.Warning("HttpRequestParser.OnGetDataSize does not know Connection: {0}", value);
                    }
                }
                else
                {
                    //Cannot determine the length
                    result = 0;
                    mError = HttpParserFailureReason.NoDataLength;
                }
            }

            return result;
        }
        #endregion

        #region On Process First Line
        /// <summary>
        /// This method is raised the very first line reading is completed.
        /// </summary>        
        /// <param name="buffer">The buffer to read line data from.</param>
        /// <param name="size">Number of bytes the line occupies.</param>
        /// <param name="content">The content object for saving parsed data to.</param>
        protected override HttpParserFailureReason OnProcessFirstLine(byte[] buffer, int size, IContextReader reader, IHttpContent content)
        {
            HttpParserFailureReason result = HttpParserFailureReason.None;
            IHttpRequest request = (IHttpRequest)content;

            try
            {
                #region parse protocol items

                //EXAMPLE OF PROPER FIRST LINE                
                //GET /someUrl HTTP/1.1

                //find method
                int startIdx = 0;
                int endIdx = buffer.IndexOf(SpaceCharactorAsByte, 0, size);
#if SILVERLIGHT
                Encoding encode = Encoding.UTF8;
#else
                Encoding encode = Encoding.ASCII;
#endif
                if (endIdx > 0)
                {
                    request.MethodName = encode.GetString(buffer, startIdx, endIdx - startIdx);

                    //find path
                    startIdx = endIdx + 1;
                    endIdx = buffer.IndexOf(SpaceCharactorAsByte, startIdx, size);

                    if (endIdx > 0)
                    {
                        request.Path = encode.GetString(buffer, startIdx, endIdx - startIdx);

                        //find version
                        startIdx = endIdx + 1;
                        if (startIdx < size)
                        {
                            request.Version = encode.GetString(buffer, startIdx, size - startIdx);
                        }
                        else
                        {
                            //could not find Http version
                            result = HttpParserFailureReason.NoHttpVersion;

                            #region Tracing
#if DEBUG || TESTING
                            if (NetSettings.PublishWarning)
                            {
                                Log.Warning("Could not find HTTP version");
                            }
#endif
                            #endregion
                        }
                    }
                    else
                    {
                        //could not find path
                        result = HttpParserFailureReason.NoPath;

                        #region Tracing
#if DEBUG || TESTING
                        if (NetSettings.PublishWarning)
                        {
                            Log.Warning("Could not find status code");
                        }
#endif
                        #endregion
                    }
                }
                else
                {
                    //could not determine method
                    result = HttpParserFailureReason.NoMethod;

                    #region Tracing
#if DEBUG || TESTING
                    if (NetSettings.PublishWarning)
                    {
                        Log.Warning("Could not find HTTP method");

                    }
#endif
                    #endregion
                }

                #endregion
            }
            catch (Exception ex)
            {
                #region Tracing
                if (NetSettings.PublishError)
                {
                    Log.Error("Cannot parse response first line", ex);
                }
                #endregion
                result = HttpParserFailureReason.Unspecified;
            }

            return result;
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public HttpRequestParser()
            : base()
        { }
        #endregion
    }
}
